#include "XJ/PanelXJ_TCPClient.h"
#include "ui_PanelXJ_TCPClient.h"


PanelXJ_TCPClient::PanelXJ_TCPClient(QWidget *parent) :
    QWidget(parent),ui(new Ui::PanelXJ_TCPClient)    //南瑞继保 103 默认tcp端口哦6000
{
    ui->setupUi(this);

    ui->lineEditTcpServerAddr->setText("192.168.0.220"); //192.168.0.220
    ui->lineEditTcpServerPort->setText("6000");

    connect(ui->pushButtonSend, &QPushButton::clicked, this, &PanelXJ_TCPClient::slot_send);
    connect(ui->pushButtonConnect, &QPushButton::clicked, this, &PanelXJ_TCPClient::slot_connect);

    m_client = new XJConnection;
    m_client->setParent(0);

    ui->pushButtonSend->setEnabled(false);

    ui->pushButtonConnect->setText("连接");

    ui->comboBoxLocalHostAddr->addItems(m_client->getLocalHostIPList());

    ui->radioButtonHeart->setEnabled(false);
    ui->pushButtonSendCombox->setEnabled(false);

    // 连接状态刷新界面控件状态
    connect(m_client, &XJConnection::sig_disconnect, this, &PanelXJ_TCPClient::slot_updateUiAsDisconnect);
    connect(m_client, &XJConnection::sig_conncted, this, &PanelXJ_TCPClient::slot_updateUiAsConnected);
    connect(m_client, &XJConnection::sig_sendMsg, this, &PanelXJ_TCPClient::slot_updateUiAsSend);

    // 将报文解析结果传给 定值显示界面
   // connect(&m_Parser, SIGNAL(sig_parseFinished(QStringList,int)), &m_panelBill, SLOT(onRecv(QStringList, int)));

    // 接收 tcp 消息
    connect(m_client, &XJConnection::sig_readyRead, this, &PanelXJ_TCPClient::slot_recv);

    // 标题解析结束束是解析定值模板的前题
    connect(&m_Parser, &XJ103_Parser::sig_getTitlesFinished, this, &PanelXJ_TCPClient::slot_setCanReadBillInfo);

    // 显示定值信息, 正式解析 存在 m_recvList 中的报文为可读
    connect(ui->pushButtonShowBill, &QPushButton::clicked, this, &PanelXJ_TCPClient::slot_pushButtonShowBill_clicked);
}

PanelXJ_TCPClient::~PanelXJ_TCPClient()
{
    delete ui;
    delete m_client;
}

void PanelXJ_TCPClient::connectDevice(QString devAddr, QString devPort, QString localAddr, QString localPort)
{
    slot_connect();
}

void PanelXJ_TCPClient::readDeviceAll()
{
    slot_pushButtonReadAll_clicked();
}

void PanelXJ_TCPClient::showTable()
{
    m_panelBill.show();
}

void PanelXJ_TCPClient::slot_send()
{
    QString m_sendMsg = ui->lineEditTcpMsg->text();
    emit sig_sendClicked();
    m_sendMsg.remove(' ');
    m_client->sendTcpMsg(m_sendMsg);
}

void PanelXJ_TCPClient::slot_recv()
{
     ui->textBrowserRecv->append("[接收]: " +  m_client->getRecvTcpMsg().toHex());

     //解析接受到的报文,将接受报文传给解析逻辑层
     QByteArray recvMsgBytes =  m_client->getRecvTcpMsg();
    // qDebug() << "收到的原始byte 数据 " << recvMsgBytes;

     m_recvList.append(recvMsgBytes);   // 具体解析这一步可以推迟到用户点击展示的时候，先保存全部接收到的数据

     // 将报文原始数据传到解析层 2021.04.20 下午
     m_Parser.parseSFPackets(recvMsgBytes);
}

void PanelXJ_TCPClient::slot_connect()
{
    m_timerConnectDev.start();
    emit sig_connect();
}

void PanelXJ_TCPClient::slot_updateUiAsDisconnect()
{
    ui->lineEditTcpServerAddr->setEnabled(true);
    ui->lineEditTcpServerPort->setEnabled(true);
    ui->comboBoxLocalHostAddr->setEnabled(true);
    ui->pushButtonConnect->setEnabled(true);

    ui->radioButtonHeart->setEnabled(false);
    ui->pushButtonSend->setEnabled(false);
    ui->pushButtonConnect->setText("连接");
    ui->pushButtonSendCombox->setEnabled(false);
    ui->pushButtonSend->setEnabled(false);
    ui->radioButtonHeart->setChecked(false);
}

void PanelXJ_TCPClient::slot_updateUiAsConnected()
{
    ui->pushButtonSend->setEnabled(true);
    ui->pushButtonConnect->setText("断开");
    ui->lineEditTcpServerPort->setEnabled(false);
    ui->lineEditTcpServerAddr->setEnabled(false);
    ui->radioButtonHeart->setEnabled(true);
    ui->comboBoxLocalHostAddr->setEnabled(false);
    ui->pushButtonSendCombox->setEnabled(true);
}

void PanelXJ_TCPClient::slot_updateUiAsSend(QString sendMsg)
{
    ui->textBrowserRecv->append(sendMsg);
}

void PanelXJ_TCPClient::on_pushButtonConnect_clicked()
{
    if (ui->pushButtonConnect->text() == "连接")
    {
        // 从界面获取通讯参数，传给tcp 服务层，以备报文构造使用
        m_client->setIPPortAndConnect( ui->lineEditTcpServerAddr->text(), ui->comboBoxLocalHostAddr->currentText(), ui->lineEditTcpServerPort->text());
    }
    // 断开连接
    else
    {
        m_client->disconnectFromDevice();
    }
}


void PanelXJ_TCPClient::on_pushButtonClear_clicked()
{
    ui->textBrowserRecv->clear();
    m_Parser.clearTalbleStructBuffer();
}

void PanelXJ_TCPClient::on_pushButtonSendCombox_clicked()
{
    // 发送心跳
    int index = ui->comboBox->currentIndex();
    if (index == 0)
    {
        //QByteArray  heartCmd = "90eb1400000090eb0000dc000000010000002b00500000000000ffff";
        m_client->startHeartTimer();
    }
    else if (index == 1)
    {
        QByteArray readTitleCmd = "";
        readTitleCmd = m_nrjbPacketConstructer.constructReadAllTitles(ui->lineEditTcpServerAddr->text(), ui->comboBoxLocalHostAddr->currentText());
        m_client->sendTcpMsg(readTitleCmd);
    }
}


void PanelXJ_TCPClient::on_radioButtonHeart_clicked(bool checked)
{
    if(checked == true)
    {
        m_client->startHeartTimer();
    }
    else
    {
        m_client->stopHeartTimer();
    }
}

void PanelXJ_TCPClient::slot_pushButtonShowBill_clicked()
{
    //获取解析接收到的全部报文
//    foreach (QByteArray packet, m_recvList)
//    {
//        m_Parser.parseNRJBPackets(packet);
//    }

    QList<QStringList>  billTableInfo =  m_Parser.getBillTablesInfo();

    // 表格结构信息传个界面
    m_panelBill.showBillTables(billTableInfo);

}

void PanelXJ_TCPClient::on_pushButtonReadGroup_clicked()
{
    QString  groupNo  = ui->lineEditGroupNo->text();       // 用户输入10进制组号

    QString kod;
    // 描述
    if (ui->comboBoxRequireKOD->currentText().contains("描述"))
    {
        kod = KOD_DESCRIPTER;
    }
    else if (ui->comboBoxRequireKOD->currentText().contains("实际值"))
    {
        kod = KOD_REAL_VALUE;
    }
    else if (ui->comboBoxRequireKOD->currentText().contains("默认值"))
    {
        kod = KOD_DEFAULT_VALU;
    }
    // 目标设备地址
    ushort srcAddr = Utils::uintStrToHexStr(ui->comboBoxLocalHostAddr->currentText().split('.')[3],4).toUInt(nullptr,16);
    ushort destAddr = (Utils::uintStrToHexStr(ui->lineEditTcpServerAddr->text().split('.')[3],4)).toUInt(nullptr,16);
    qDebug() << "src addr " << Utils::uintStrToHexStr(ui->comboBoxLocalHostAddr->currentText().split('.')[3],4) << srcAddr << "dest addr " << destAddr;

    // 读取单个
    QByteArray cmdReadGroup =  m_nrjbPacketConstructer.constructReadGroupInfo(srcAddr, destAddr, groupNo, kod);

    ui->lineEditTcpMsg->setText(cmdReadGroup);
}


void PanelXJ_TCPClient::readAllGroupsInfo()
{
    ushort destAddr = Utils::uintStrToHexStr(ui->lineEditTcpServerAddr->text().split('.')[3], 4).toUInt(nullptr,16);
    ushort srcAddr = Utils::uintStrToHexStr(ui->comboBoxLocalHostAddr->currentText().split('.')[3], 4).toUInt(nullptr,16);

    // 请求全部组的具体信息
    QByteArrayList cmdList;
    QByteArray tmpCmd;

    QStringList kodLiST = {KOD_DESCRIPTER/*, KOD_REAL_VALUE, KOD_UNIT, KOD_DIMENSION*/};
    foreach (QString it, m_Parser.getAboutBillGroupInfo().keys())
    {
        qDebug() << "***************************第 " << it << " 组***************************";
        foreach (QString it_kod, kodLiST)
        {
            qDebug() << "***************************第 " << it << " 组***************************";
            tmpCmd = m_nrjbPacketConstructer.constructReadGroupInfo(srcAddr, destAddr, it, it_kod);
            cmdList.append(tmpCmd);
        }
    }
    m_client->sendTcpMsg(cmdList);
}

void PanelXJ_TCPClient::readAllTitlesInfo()
{
    // 要清除上次接收保存的缓存数据
//    m_Parser.m_groupInfoMap.clear();
    QByteArray readTitleCmd = "";
    readTitleCmd = m_nrjbPacketConstructer.constructReadAllTitles(ui->lineEditTcpServerAddr->text(), ui->comboBoxLocalHostAddr->currentText());
    m_client->sendTcpMsg(readTitleCmd);
}

// 读取所有的信息
void PanelXJ_TCPClient::slot_pushButtonReadAll_clicked()
{
    m_recvList.clear();
    // 第一步先请求标题数据
    readAllTitlesInfo();
}

void PanelXJ_TCPClient::slot_setCanReadBillInfo()
{
//    m_canGetBillInfo = true;
    ui->textBrowserRecv->append("**** 可以读取定值信息。****");
    readAllGroupsInfo();
}
